<?php
namespace app\admin\controller;

use app\common\model\facade\Captcha;
use app\common\model\UserMain;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Account
{
    public function login()
    {
        if (Request::isPost() && Request::isAjax()) {
            if (!Captcha::check(Request::post('verify_code/s'))) {
                return show_error('验证码输入错误');
            }
            if (!$account = Request::post('account/s')) {
                return show_error('请输入用户名');
            }
            if (!$password = Request::post('password/s')) {
                return show_error('请输入用户密码');
            }
            $type = 'username';
            if (Validate::isEmail($account)) {
                $type = 'email';
            } else if (Validate::isMobile($account)) {
                $type = 'mobile';
            }
            if (!$user = UserMain::where($type, '=', $account)->find()) {
                return show_error('账号不存在！');
            }
            if ($user['status'] < 1) {
                return show_error('用户状态不允许进行当前操作');
            }
            if (!password_verify(md5($password), $user['password'])) {
                return show_error('密码错误！');
            }
            if ($user['type'] !== 'system') {
                return show_error('无权操作！');
            }
            $user->login();
            return show_success('登陆成功', url('admin/index/index'), '', -1);
        }
        return View::config(['layout_on' => false])->fetch();
    }

    public function logout()
    {
        (new UserMain)->logout();
        return redirect('admin/account/login');
    }
}
